package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //TCP是有连接的，socket对象会保存IP和端口号
        //TcpEchoClient类就不需要保存了
        socket = new Socket(serverIp,serverPort);
        //执行这行代码，就会和对应的服务器进行连接TCP的连接 在系统内核完成
    }

    public void start(){
        System.out.println("客户端~~启动！！！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetWork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                System.out.print("-> ");
                //1. 从控制台读取请求
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request = scannerConsole.next();

                //2. 把请求发给服务器
                //使用println发送，为了让发送的请求末尾带有换行
                //和服务器 scanner接收信息 呼应
                writer.println(request);
                //手动冲刷缓冲区 确保数据真的发出去
                writer.flush();

                //3. 从服务器读取响应
                //使用scanner.next（）接收 与服务器使用PrintWriter写回 呼应
                String response = scannerNetWork.next();

                //4. 把响应显示出来
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
